import Vue from 'vue'
import Router from 'vue-router'
import routers from './routerData'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import lazyRoute from '@/utils/menuLoad.js'
import { err404 } from '@/router/routerData.js'
import store from '../store/index.js'
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(Router)

export const constantRoutes = routers

const createRouter = () =>
  new Router({
    base: '/',
    mode: 'history',
    //页面每次打开滚到最顶部
    scrollBehavior: () => ({ y: 0 }),
    routes: constantRoutes
  })

const router = createRouter()

nprogress.configure({ showSpinner: false })

//创建动态路由
function createNewRouter() {
  let routeStore = store.state.menuData
  let routeData = JSON.parse(JSON.stringify(routeStore))
  routeData.forEach(item => {
    if (item.component != 'BasicLayout') {
      let children = JSON.parse(JSON.stringify(item))
      item.children.push(children)
      item.component = 'BasicLayout'
      item.key = item.path
      item.path = '/'
    }
  });

  let data = filterTree(routeData)
  router.addRoutes([...data, err404])
  oneRun = false;
};

//递归过滤树
function filterTree(treeArr) {
  function findItem(arr) {

    let res = arr.filter(item => {
      if (item.children && item.children.length > 0) {
        if (item.children[0].hidden != true) {
          item.redirect = item.children[0].path
        }
        item.children = findItem(item.children)
      }
      item.component = lazyRoute(item.component)
      return item
    })
    return res
  }
  return findItem(treeArr)
}


let oneRun = true; //通过oneRun变量控制 避免陷入死循环
//路由白名单
let whiteList = ['login', 'auth',  '404']
router.beforeEach((to, from, next) => {
  if (whiteList.indexOf(to.name) == -1) {
    if (store.state.routerData.length > 0) {
      if (oneRun && store.state.routerData.length > 0) {
        //页面刷新后动态路由会清空，所以需要重新创建动态路由
        createNewRouter();
        nprogress.start()
        next({
          path: `${to.fullPath}`,
          replace: true
        })
      } else {
        next()
      }
    } else {
      next({
        path: `/auth`
      })
    }

  } else {
    next()
  }

})




router.afterEach(() => {
  nprogress.done()
})

export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // 重置 路由
}

export default router
